package com.auxgroup.hr.front.commons.security;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExpiredCredentialsException;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * @author ye.meng@ssitsh.com
 * @since 1.0.0 create date 2017年10月16日
 * 自定义Filter处理类
 */
public class OAuthAuthenticatingFilter extends AccessControlFilter{
	private static final Logger logger = LoggerFactory.getLogger(OAuthAuthenticatingFilter.class);
	
	/*
	 * 访问拒绝处理
	 * true  需要继续处理
	 * false 已处理直接返回
	 */
	@Override
	protected boolean onAccessDenied(ServletRequest request,
			ServletResponse response) throws Exception {
		return false;
	}

	/*
	 *是否允许访问处理
	 */
	@Override
	protected boolean isAccessAllowed(ServletRequest request,
			ServletResponse response, Object mappedValue) throws AuthenticationException {
		try {
			OAuthToken token= new OAuthToken(((HttpServletRequest) request)
					.getHeader("Authorization"));
			// 委托给 Realm 进行登录
			getSubject(request, response).login(token);
		} catch (AuthenticationException e) {
			logger.error("invoking OAuthAuthenticatingFilter AuthenticationException :",e);
			if(e instanceof ExpiredCredentialsException){
				HttpServletResponse rsp=(HttpServletResponse)response;
				rsp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
				return false;
			}
			throw e;
		}
		return true;
	}




}
